package cn.fl.customer.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cmm.base.framework.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.service.ICstCorpTeamService;
import cn.fl.customer.vo.CstCorpTeamResumeVO;
import cn.fl.customer.vo.CstCorpTeamVO;
import cn.fl.customer.vo.CstNpSocialRlVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.service.ISysDictionaryService;
import fl.customer.facade.customer.condition.CstCorpTeamQueryCondition;
import fl.customer.facade.customer.constant.CustomerConstant;
import fl.customer.facade.customer.dto.CstCorpTeamDTO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @Description: 法人企业团队信息表 控制层
 */
@Controller
@RequestMapping("/customer/cstcorpteam")
public class CstCorpTeamController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CstCorpTeamController.class);

	/**
	 * CstCorpTeam 服务层BEAN
	 */
	@Autowired
	private ICstCorpTeamService cstCorpTeamService;
	
	/**
	 * CstBscInfo 服务层BEAN
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	
	
	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryService sysDictionaryService;

	/**
	 * 新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET})
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		String cstId = request.getParameter("cstId");
		String ctId = request.getParameter("ctId");
		ModelAndView view = new ModelAndView("customer/cstcorpteam/cstCorpTeamAdd");
		//证件类型
		List<KeyValueVO> certTypCdList = this.cstBscInfoService.searchCertTypCdList(CustomerConstant.CST_TYP_CD_NP);
		try {
			// 证件类型
			List<String> codeGrpCdList = new ArrayList<>();
			codeGrpCdList.add(DictionaryConstant.CODE_GRP_M_TYP_CD);
			codeGrpCdList.add(DictionaryConstant.CODE_GRP_GENDER_CD);
			Map<String, List<KeyValueVO>> dicMap = this.sysDictionaryService.getMultiKvList(CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd(), codeGrpCdList);
			view.addObject("searchSelectGenderCdList", dicMap.get(DictionaryConstant.CODE_GRP_GENDER_CD));// 性别状况
			view.addObject("searchSelectMTypCdList", dicMap.get(DictionaryConstant.CODE_GRP_M_TYP_CD));
		} catch (Exception e) {
			BaseLogUtils.error(logger, "toAddPage", "获取基础信息错误!" + e.getMessage());
		}
		view.addObject("searchSelectCertTypCdList", certTypCdList);
		view.addObject("cstId", cstId);
		view.addObject("ctId", ctId);
		return view;
	}
	
	/**
	 * 详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String ctId = request.getParameter("ctId");
		ModelAndView view = new ModelAndView("customer/cstcorpteam/cstCorpTeamDetail");
		view.addObject("ctId", ctId);
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String cstId = request.getParameter("cstId");
		String isEncrypt=request.getParameter("isEncrypt");

		if(StringUtils.isEmpty(cstId)){
			ListPageVO<CstNpSocialRlVO> listPage = new ListPageVO<CstNpSocialRlVO>(new ArrayList<CstNpSocialRlVO>(), 0);
			return listPage;
		}
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CstCorpTeamQueryCondition qc = new CstCorpTeamQueryCondition();
		List<Long> cstIdList = new ArrayList<>();
		cstIdList.add(Long.valueOf(cstId));
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		qc.setCstIdList(cstIdList);
		page.setCondition(qc);
		//page.setEveryPage(Integer.MAX_VALUE);//最大数据量
		logger.info("==初始化列表数据.==");
		Pager pager = this.cstCorpTeamService.searchListPage(page);
		String roleIsEncrypt=this.sysDictionaryService.getRoleisEncrypt();

		List<CstCorpTeamDTO> list = (List<CstCorpTeamDTO>) pager.getResultList();
		if (StringUtils.isNotEmpty(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(roleIsEncrypt)) {
			for (CstCorpTeamDTO dto:list ) {
				dto.setCertNo(EncryptUtil.certNoEncrypt(dto.getCertNo()));
				dto.setMp1(EncryptUtil.mobileEncrypt(dto.getMp1()));
				dto.setMp2(EncryptUtil.mobileEncrypt(dto.getMp2()));
			}
		}
		ListPageVO<CstCorpTeamDTO> listPage = new ListPageVO<CstCorpTeamDTO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("参数不完整！");
			return result;
		}
		try {
			List<Long> idList = new ArrayList<Long>();
			idList.add(Long.valueOf(id));
			boolean pass = this.cstCorpTeamService.removeByIds(idList);
			if(!pass){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("删除失败");
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("删除失败");
			logger.error("删除失败!"+ex.getMessage(), ex);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String isEncrypt=request.getParameter("isEncrypt");

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("参数不完整！");
			return result;
		}
		
		try {
			CstCorpTeamVO vo = this.cstCorpTeamService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在！");
			}else {
				String roleIsEncrypt=this.sysDictionaryService.getRoleisEncrypt();
				if (StringUtils.isNotEmpty(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(roleIsEncrypt)) {
					vo.setCertNo(EncryptUtil.certNoEncrypt(vo.getCertNo()));
					vo.setMp1(EncryptUtil.mobileEncrypt(vo.getMp1()));
					vo.setMp2(EncryptUtil.mobileEncrypt(vo.getMp2()));
				}
			}
			result.setData(vo);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("获取数据失败！");
			logger.error("获取数据失败！", ex);
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		try {
			CstCorpTeamVO entity = getRequestParams(request);
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			entity.setCrtTm(new Date());
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//检查这个新增的类型是不是唯一类型,检查类型有法人代表、董事长
			if(entity.getMTypCd().equals(DictionaryConstant.CODE_GRP_M_TYP_CD_1) ||
					entity.getMTypCd().equals(DictionaryConstant.CODE_GRP_M_TYP_CD_4)){
				CstCorpTeamQueryCondition cstCorpTeamQueryCondition = new CstCorpTeamQueryCondition();
				List<Long> cstIdList = new ArrayList<>();
				cstIdList.add(entity.getCstId());
				cstCorpTeamQueryCondition.setCstIdList(cstIdList);
				cstCorpTeamQueryCondition.setmTypCd(entity.getMTypCd());
				cstCorpTeamQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());
				List<CstCorpTeamVO> checkList = this.cstCorpTeamService.searchList(cstCorpTeamQueryCondition);
				if(CollectionUtils.isNotEmpty(checkList)){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("本类型数据已经存在,不能重复添加!");
					return result;
				}
			}
			
			Long id = this.cstCorpTeamService.add(entity);
			if(StringUtils.isNotEmpty(id)){
				result.setData(id);
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("新增失败!");
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("新增失败!");
			logger.error("", ex);
		}

		return result;
	}

	/**
	 * 获取新增修改参数
	 */
	private CstCorpTeamVO getRequestParams(HttpServletRequest request) {
		String mTypCd = request.getParameter("mTypCd");//成员类型
		String mNm = request.getParameter("mNm");//姓名
		String mp1 = request.getParameter("mp1");//手机号
		String mp2 = request.getParameter("mp2");//手机号
		String certTypCd = request.getParameter("certTypCd");//证件类型
		String certNo = request.getParameter("certNo");//证件号码
		String teamRem = request.getParameter("teamRem");//备注
		String officeTel = request.getParameter("officeTel");//办公电话
		String cstId = request.getParameter("cstId");//客户ID
		String homeAddr = request.getParameter("homeAddr");
		String birthday = request.getParameter("birthday");
		String genderCd = request.getParameter("genderCd");
		
		if(StringUtils.isEmpty(cstId) || !StringUtils.isNumeric(cstId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请确保客户信息存在后在进行操作!");
		}
		
		if(StringUtils.isEmpty(mTypCd)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请选择成员类型!");
		}
		
		if(StringUtils.isEmpty(mNm) || mNm.length() > 50 || !StringUtils.isCustomerName(mNm)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "姓名不能为空,支持格式[艾合买提•倪格提],并且长度不能大于20个字符。");
		}
		
		if(StringUtils.isNotEmpty(mp1) && !StringUtils.checkMobileNumber(mp1)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的手机号1!");
		}
		
		if(StringUtils.isNotEmpty(mp2) && !StringUtils.checkMobileNumber(mp2)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的手机号2!");
		}
		
		if(StringUtils.isNotEmpty(mp1) && StringUtils.isNotEmpty(mp2) && mp1.equals(mp2)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "手机号1不能与手机号2相同!");
		}
		
		if(StringUtils.isNotEmpty(officeTel) && !StringUtils.isFixedPhone(officeTel)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的办公电话!");
		}
		
		
		if (StringUtils.isBlank(certTypCd)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请选择证件类型!");
		}

		/*if (StringUtils.isBlank(certNo)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "证件号码不能为空!");
		}*/

		if (StringUtils.isNotEmpty(certNo) && certTypCd.equals(DictionaryConstant.CODE_CERT_TYP_CD_0) && !StringUtils.isIdCardNumber(certNo)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请输入正确的身份证号码!");
		}
		
		
		CstCorpTeamVO entity = new CstCorpTeamVO();
		entity.setMTypCd(mTypCd);
		entity.setMNm(mNm);
		entity.setMp1(mp1);
		entity.setMp2(mp2);
		entity.setOfficeTel(officeTel);
		entity.setTeamRem(teamRem);
		entity.setCertTypCd(certTypCd);
		entity.setCertNo(certNo);
		entity.setCstId(Long.valueOf(cstId));
		entity.setHomeAddr(homeAddr);
		entity.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		entity.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		entity.setGenderCd(genderCd);
		entity.setBirthday(birthday);
		//解析简历信息
		List<CstCorpTeamResumeVO> resumeList = new ArrayList<>();
		String resumeGridData = request.getParameter("resumeGrid");
		if(StringUtils.isNotEmpty(resumeGridData)){
			JSONArray resumeJA = JSONArray.fromObject(resumeGridData);
			CstCorpTeamResumeVO cstCorpTeamResumeVO = null;
			Long usrId = CurrentThreadContext.getCurrentUserId();
			for (Object object : resumeJA) {
				JSONObject resumeJO = (JSONObject)object;
				if(null == resumeJO)continue;
				cstCorpTeamResumeVO = new CstCorpTeamResumeVO();
				//处理时间
				String sDtStr = resumeJO.optString("startDtStr", "");
				String eDtStr = resumeJO.optString("endDtStr", "");
				Date sDt = DateUtils.formatStringToDate(sDtStr, DateUtils.YYYY_MM_DD);
				Date eDt = DateUtils.formatStringToDate(eDtStr, DateUtils.YYYY_MM_DD);
				if(StringUtils.isEmpty(sDtStr) || StringUtils.isEmpty(eDtStr) || null == eDt){
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "开始时间和结束时间不能为空!");
				}
				
				
				if(sDt.after(eDt)){
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "开始时间不能大于结束时间!");
				}
				
				cstCorpTeamResumeVO.setId(resumeJO.optLong("id"));
				cstCorpTeamResumeVO.setIsDel(BaseConstant.IS_YESNO_NO);
				cstCorpTeamResumeVO.setStartDt(sDt);
				cstCorpTeamResumeVO.setEndDt(eDt);
				cstCorpTeamResumeVO.setMemId(null);
				cstCorpTeamResumeVO.setPost(resumeJO.optString("post", ""));
				cstCorpTeamResumeVO.setWorkPlc(resumeJO.optString("workPlc", ""));
				cstCorpTeamResumeVO.setCrtTm(new Date());
				cstCorpTeamResumeVO.setCrtUsrId(usrId);
				resumeList.add(cstCorpTeamResumeVO);
			}
		}
		entity.setResumeList(resumeList);
		return entity;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("参数不完整！");
			return result;
		}
		try {
			CstCorpTeamVO cstCorpTeamVO = getRequestParams(request);
			cstCorpTeamVO.setMdfTm(new Date());
			cstCorpTeamVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			cstCorpTeamVO.setId(Long.valueOf(id));
			
			//检查这个新增的类型是不是唯一类型,检查类型有法人代表、董事长
			String mTypCd = cstCorpTeamVO.getMTypCd();
			if(mTypCd.equals(DictionaryConstant.CODE_GRP_M_TYP_CD_1) ||
					mTypCd.equals(DictionaryConstant.CODE_GRP_M_TYP_CD_4)){
				CstCorpTeamQueryCondition cstCorpTeamQueryCondition = new CstCorpTeamQueryCondition();
				List<Long> cstIdList = new ArrayList<>();
				cstIdList.add(cstCorpTeamVO.getCstId());
				cstCorpTeamQueryCondition.setCstIdList(cstIdList);
				cstCorpTeamQueryCondition.setmTypCd(mTypCd);
				cstCorpTeamQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());
				List<CstCorpTeamVO> checkList = this.cstCorpTeamService.searchList(cstCorpTeamQueryCondition);
				if(CollectionUtils.isNotEmpty(checkList)){
					Boolean tip = false;
					for (CstCorpTeamVO cstCorpTeamVO2 : checkList) {
						if(!cstCorpTeamVO2.getId().equals(Long.valueOf(id))){//主键不相等说明其它记录已经有了同样的类型,不通过
							tip = true;
							break;
						}
					}
					if(tip){
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("本类型数据已经存在,不能重复添加!");
						return result;
					}
				}
			}
			
			
			boolean success = this.cstCorpTeamService.modify(cstCorpTeamVO);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败！");
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("修改失败!");
			logger.error("修改失败!", ex);
		}
		return result;
	}
}

